package com.avalon.erp.addon.pet.service.user.share;

import com.avalon.core.field.Field;
import com.avalon.core.field.Fields;
import com.avalon.core.model.Record;
import com.avalon.core.model.RecordRow;
import com.avalon.core.service.AbstractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class PetShareCommentLikeService extends AbstractService {
    @Override
    public String getServiceName() {
        return "pet.share.comment.like";
    }

    public final Field commentId = Fields.createMany2one("评论id", "pet.share.comment");
    public final Field userId = Fields.createMany2one("用户id", "pet.user");
    public final Field thumbUp = Fields.createBoolean("点赞"); // true 表示之前点赞过，false 点赞之后取消了，没有记录 则表示没有点赞过

    /**
     * 评论点赞
     *
     * @param shareCommentId 评论id
     * @param userId         用户id
     * @param like           0 取消点赞 1 点赞
     */
    public void shareCommentLike(Integer shareCommentId, Integer userId, Integer like) {
        if (like.equals(1)) {
            Record select = select(
                    commentId.eq(shareCommentId).andEqualCondition(this.userId, userId),
                    getPrimaryKeyName());
            RecordRow recordRow = null;
            if (select.isEmpty()) {
                recordRow = RecordRow.build();
                recordRow.put(commentId, shareCommentId);
                recordRow.put(this.userId, userId);
                recordRow.put(thumbUp, true);
                insert(recordRow);
            } else {
                recordRow = select.get(0);
                recordRow.put(thumbUp, true);
                update(recordRow);
            }
        } else {
            //取消点赞
            Record select = select(commentId.eq(shareCommentId).andEqualCondition(this.userId, userId),
                    getPrimaryKeyName());
            RecordRow recordRow = null;
            if (!select.isEmpty()) {
                recordRow = select.get(0);
                recordRow.put(thumbUp, false);
                update(recordRow);
            }
        }
    }

    public Integer getCommentUserLike(Integer shareCommentId, Integer userId) {
        Record select = select(commentId.eq(shareCommentId).andEqualCondition(this.userId, userId),
                "id", "thumbUp");
        if (select.isEmpty()) {
            return 0;
        } else {
            return select.get(0).getBoolean(thumbUp) ? 1 : 0;
        }
    }
}
